package com.cyzy.service.impl;

import com.cyzy.entity.EmailVerificationCode;
import com.cyzy.service.EmailService;
import com.cyzy.utils.CodeGenerator;
import com.cyzy.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

/**
 * @author LIGHT
 */
@Service
public class EmailServiceImpl implements EmailService {

    private final MailSender mailSender;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String EMAIL_CODE_PREFIX = "";
    private static final long CODE_EXPIRE_SECONDS = 300; // 5分钟过期

    /**
     * 验证码有效期（分钟）
     */
    private static final int CODE_EXPIRE_MINUTES = 5;

    /**
     * 验证码长度
     */
    private static final int CODE_LENGTH = 6;

    public EmailServiceImpl(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Override
    public void sentEmail(String to, String subject, String text) {
        System.out.println("尝试发送邮箱");
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("15980174862@163.com");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
        System.out.println("发送成功");
    }

    @Override
    public String sendVerificationCode(String email) {
        // 生成6位数字验证码
        String code = CodeGenerator.generateNumericCode(CODE_LENGTH);

        // 存储验证码到Redis，设置5分钟过期
        String redisKey = EMAIL_CODE_PREFIX + Md5Util.getMD5String(email);
        redisTemplate.opsForValue().set(redisKey, code, CODE_EXPIRE_SECONDS, TimeUnit.SECONDS);

        // 发送验证码邮件
        String subject = "登录验证码";
        String content = "您的验证码是：" + code + "，有效期" + CODE_EXPIRE_MINUTES + "分钟，请勿泄露给他人。";
        sentEmail(email, subject, content);

        return code;
    }

    @Override
    public boolean verifyCode(String email, String code) {
        String redisKey = EMAIL_CODE_PREFIX + Md5Util.getMD5String(email);
        String storedCode = redisTemplate.opsForValue().get(redisKey);

        // 验证码不存在或已过期
        if (storedCode == null) {
            return false;
        }

        // 验证码不匹配
        if (!storedCode.equals(code)) {
            return false;
        }

        // 验证成功，删除验证码
        redisTemplate.delete(redisKey);
        return true;
    }
}
